import os

import ddt
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from testconfig import config

from framework.selenium.seleniumbasetest import SeleniumBaseTest
from lib.web.webtask import WebTasks

timeout = 30


@ddt.ddt()
class WebTest(SeleniumBaseTest):

    def setUp(self):
        super().setUp(config=config)

    def tearDown(self):
        super().tearDown()

    @ddt.data('BrowserChrome')
    def baidu_test(self, device_name):
        self.init_driver_by_browser_name(config, deviceName=device_name)
        self.web_tasks = WebTasks(self.driver)
        ret = self.web_tasks.kw_search_in_baidu('王者荣耀')

        self.logger.info(f'百度搜索测试结果 => {ret}')
        self.assertTrue(ret, '百度搜索测试失败')

    @ddt.data('BrowserChrome')
    def fileupload_test(self, device_name):
        self.init_driver_by_browser_name(config, deviceName=device_name)

        wait = WebDriverWait(self.driver, timeout=timeout)
        url = 'https://the-internet.herokuapp.com'
        self.logger.info(f'打开网站{url}')
        self.driver.get(url)

        link_txt = 'File Upload'
        self.logger.info(f'单击{link_txt}')
        upload_link = wait.until(EC.presence_of_element_located((By.LINK_TEXT, link_txt)))
        upload_link.click()

        file_name = 'sample.pdf'
        self.logger.info(f'上传文件{file_name}')
        file_upload = wait.until(EC.presence_of_element_located((By.ID, 'file-upload')))
        file_fullpath = os.path.join(os.path.sep, self.project_path_root, 'files', file_name)
        file_upload.send_keys(file_fullpath)
        self.driver.find_element(By.ID, 'file-submit').click()

        uploaded = wait.until(EC.presence_of_element_located((By.ID, 'uploaded-files')))
        ret = True if file_name == uploaded.text else False
        self.logger.info(f'上传结果校验 => {ret}')
        self.assertTrue(ret, f'上传结果校验失败！')
